﻿using System;
using System.Diagnostics;
using System.Linq;

namespace Borg.Framework
{
    public static class ExitAction
    {
        public static void Do(PlugInfo startup)
        {
            if (startup.ExtensionInfo.IsReleased)
                return;

            startup.ExtensionInfo.Release();

            if (ReadyForShutdown())
                Runtime.Shutdown();
        }

        public static void Do(object startup)
        {
            Do(Runtime.GetPlugInfo(startup, "Startup"));
        }

        public static void Do(object s, ActionEventArgs args)
        {
            var extensionInfo = args.SlotInfo.ExtensionInfo;
            var toSlot = Runtime.Repository.SlotInfos["Startup"];

            foreach (var path in extensionInfo.FindHostPaths(toSlot))
                Do(path.Connections.Last().Plug);
        }

        public static void Do(object sender, EventArgs args)
        {
            var extensionInfo = Runtime.GetExtensionInfo(sender);
            Debug.Assert(extensionInfo != null);
            Do(extensionInfo.PlugInfos["Startup"]);
        }

        private static bool ReadyForShutdown()
        {
            var si = Runtime.Repository.SlotInfos["Startup"];

            return si.PluggedPlugInfos.
                Select(pi => pi.ExtensionInfo.ExtensionTypeInfo.PlugTypeInfos[si.Name]).
                All(pti => (bool) pti.GetParamValue("UnplugOnExit"));
        }
    }
}

